import { Component, OnInit } from '@angular/core';
import * as XLSX from 'xlsx';

type AOA = any[][];

@Component({
  selector: 'app-sheet-import',
  templateUrl: './sheet-import.component.html',
  styleUrls: ['./sheet-import.component.css']
})
export class SheetImportComponent implements OnInit {

  data: AOA = [];

  constructor() { }

  ngOnInit() {
  }

  fileChange({file, type}) {
    if (type === 'start') {
      // 文件改变会产生3个状态，start process end，这里只在start时进行excel解析
      const reader = new FileReader();
      reader.onload = (e: any) => {
        /* read workbook */
        const bstr: string = e.target.result;
        const wb: XLSX.WorkBook = XLSX.read(bstr, {type: 'binary'});
        /* grab first sheet */
        const wsname: string = wb.SheetNames[0];
        const ws: XLSX.WorkSheet = wb.Sheets[wsname];
        this.data =  (XLSX.utils.sheet_to_json(ws, {header: 1})) as AOA;
        console.log(this.data);
      };
      reader.readAsBinaryString(file.originFileObj);
    }
  }

  importExcel({}) {
    // 覆盖文件上传的默认行为，这里只需读取解析excel文件，并不需要上传文件。未返回Subscription会产生一个warning
    return null;
  }
}
